import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import * as flatpickr from 'flatpickr';
import { zh } from "flatpickr/dist/l10n/zh.js";
import { environment } from "../../../../../../environments/environment";
import { HistoryChangeService } from './history-change.service';
import * as _ from "lodash";
import { ApplyFundGroupComponent } from '../../modal/apply-fund-group/apply-fund-group.component';
import { DataService } from '../../../../../services/data.service';
import { AppPaginationComponent, PaginationModel } from "../../../../../widgets/pagination/pagination.component";
import { Util } from '../../../../../common/util';
import { TablePageComponent } from '../../modal/table/table-page/table-page.component';

@Component({
  selector: 'app-history-change',
  templateUrl: './history-change.component.html',
  styleUrls: ['./history-change.component.scss'],
  providers: [HistoryChangeService]
})
export class HistoryChangeComponent implements OnInit {

  //查询历史变更记录列表
  @ViewChild("historyTablePage", { read: ViewContainerRef })
  historyTablePage: ViewContainerRef;
  tablePageComponent: ComponentRef<TablePageComponent>;
  // 适用基金组modal
  @ViewChild("applyFundGroup", { read: ViewContainerRef })
  applyFundGroup: ViewContainerRef;
  applyFundGroupComponent: ComponentRef<ApplyFundGroupComponent>;
  //全选按钮
  public isCheckedAll: any = false;
  public cloneList:any = [];
  //分页配置
  public listPageInfo = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };
  //查询条件
  public getBody = {
    pageIndex: 1,
    pageSize: 50,
    sCreateStart: '',//开始日期
    sCreateEnd: '',//结束日期
    sFileName: '',//文件名称
    f1: '',//内容
    sFundGroupds: '',//基金组
    nNdIds: ''//选择的列表数据id
  }
  public sFundGroupdsZh: any = '';
  //条目历史列表
  public listData: any = [];
  constructor(
    public resolver: ComponentFactoryResolver,
    public historyChangeService: HistoryChangeService,
    public dataService: DataService
  ) { }
  // 条数分页
  sizeChange(pageSize: number) {
    if (pageSize !== this.listPageInfo.pageSize) {
      this.listPageInfo.pageSize = pageSize;
      this.historyChange();
    }
  }
  // 列表分页
  pageNavigation(currentPageNum: number) {
    this.listPageInfo.currentPageNum = currentPageNum;
    this.historyChange(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  }
  ngOnInit() {
    // 初始化日期控件
    flatpickr.localize(zh);
    this.historyChange();
    let that = this;
    this.dataService.nQDIIInputModelEmitter = new EventEmitter();
    this.dataService.nQDIIInputModelEmitter.subscribe((value: any) => {
      if (value) {
        switch (value) {
          case 'inputModel':
            that.getBody.sFundGroupds = that.dataService.nQDIIIdList;
            that.sFundGroupdsZh = that.dataService.nQDIIFGroupInfo;
            window['$']('#applyFundGroup').modal('hide');
            break;
        }
      }
    })
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  //查询历史变更记录
  historyChange(pageNum?, pageSize?) {
    this.getBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.historyChangeService.historyChange(this.getBody).subscribe(data => {
      if (data) {
        this.listData = data.list;
        console.log(data);
        this.cloneList = _.cloneDeep(data.list);
        this.showTablePage(this.listData);
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
        this.controlDom();
      }
    })
  }
  //适用基金组modal
  showApplyFundGroup() {
    // 判断组件是否已创建，如果创建先注销
    if (this.applyFundGroupComponent && this.applyFundGroupComponent.instance) {
      this.applyFundGroupComponent.destroy();
    }
    // 动态创建组件的实例
    const applyFundGroupComponent = this.resolver.resolveComponentFactory(ApplyFundGroupComponent);
    this.applyFundGroupComponent = this.applyFundGroup.createComponent(applyFundGroupComponent);
    this.applyFundGroupComponent.instance.modeType = 'input';
    if (this.getBody.sFundGroupds != '' && this.getBody.sFundGroupds != null && this.getBody.sFundGroupds != undefined) {
      this.applyFundGroupComponent.instance.checkedIdList = this.getBody.sFundGroupds.split(',');
      console.log(this.getBody.sFundGroupds.split(','))
    }
    window['$']('#applyFundGroup').modal('show');
  }
  //导出
  exportExcel() {
    let that = this;
    // console.log("===============");
    // let checkedItem = [];
    // _.forEach(this.listData, item => {
    //   if (item.isChecked) {
    //     checkedItem.push(item.nQdId);
    //   }
    // })
    // nQdIdList=checkedItem;
    // let converItem: any = checkedItem.join(',');
    let getBody = {
      sCreateStart: this.getBody.sCreateStart,
      sCreateEnd: this.getBody.sCreateEnd,
      f1: this.getBody.f1,
      sFundGroupds: this.getBody.sFundGroupds,
      sFileName: this.getBody.sFileName,
      nNdIds: this.getBody.nNdIds
    }
    getBody.sFileName = encodeURI(this.getBody.sFileName);
    getBody.f1 = encodeURI(this.getBody.f1);
    if (Util.dateOrder(that.getBody.sCreateStart, that.getBody.sCreateEnd)) {
      const iframe = window['$']("<iframe id='downloadiframe'>");
      iframe.attr('style', 'display:none');
      //  转码，兼容ie
      // getBody.sFullName = encodeURI(getBody.sFullName)
      iframe.attr('src', environment.server + '/pms/v1/riskmanage/data/export/historyChanges?token=' + sessionStorage.getItem('token')
        + '&sCreateStart=' + getBody.sCreateStart
        + '&sCreateEnd=' + getBody.sCreateEnd
        + '&f1=' + getBody.f1
        + '&sFundGroupds=' + getBody.sFundGroupds
        + '&sFileName=' + getBody.sFileName
        + '&nNdIds=' + getBody.nNdIds
      );
      window['$']('body').append(iframe);
      setTimeout("$('#downloadiframe').remove()", 60000);
    } else {
      window['swal']("提示", "开始日期 须早于 结束日期", "warning");
    }
  }
  //搜索查询
  searchQuery() {
    let that = this;
    if (Util.dateOrder(that.getBody.sCreateStart, that.getBody.sCreateEnd)) {
      that.historyChange();
    } else {
      window['swal']("提示", "开始日期 须早于 结束日期", "warning");
    }
  }
  //根据编号是否相同操控dom
  controlDom() {
    let that = this;
    if (this.listData != null && this.listData.length > 0) {
      for (let i = 0; i < that.listData.length - 1; i++) {
        if (that.listData[i].nNjId == that.listData[i + 1].nNjId) {
          _.forIn(that.listData[i], (item1, key1) => {
            let index1 = i + 1;
            let index2 = i + 2;
            let id1 = "#route-table table tbody tr:nth-child(" + index2 + ") td div[id=" + key1 + "]";
            if (item1 == that.listData[i + 1][key1]) {
              // window['$'](id1).removeClass('font-color');
            } else {
              // window['$'](id1).addClass('font-color');
              that.cloneList[i + 1][key1] = 'red';
            }
          })
        }
      }
    }
  }
  //查询历史变更记录列表
  showTablePage(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.tablePageComponent && this.tablePageComponent.instance) {
      this.tablePageComponent.destroy();
    }

    // 动态创建组件的实例
    const tablePageComponent = this.resolver.resolveComponentFactory(TablePageComponent);
    this.tablePageComponent = this.historyTablePage.createComponent(tablePageComponent);
    this.tablePageComponent.instance.listData = item;
    this.tablePageComponent.instance.listType = '4';
    this.tablePageComponent.instance.setColor = this.cloneList;
  }
}
